package leetcode.top100;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import leetcode.util.CommonUtils;
import leetcode.剑指offer.pojo.ListNode;
import org.junit.Test;

/**
 * @author ：zsy
 * @date ：Created 2022/12/5 8:43 PM
 * @description：
 */
public class _002_两数相加 {
    @Test
    public void test() {
        ListNode l1 = CommonUtils.transferArrToListNode(new int[]{2, 4, 3});
        ListNode l2 = CommonUtils.transferArrToListNode(new int[]{5, 6, 4});
        ListNode res = new Solution().addTwoNumbers(l1, l2);
        CommonUtils.printListNode(res);
    }

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            int factor = 0;
            ListNode curHead = new ListNode(-1);
            ListNode tmp = curHead;
            while (l1 != null || l2 != null) {
                int val1 = 0, val2 = 0;
                if (l1 != null) {
                    val1 = l1.val;
                    l1 = l1.next;
                }
                if (l2 != null) {
                    val2 = l2.val;
                    l2 = l2.next;
                }
                int sum = val1 + val2 + factor;
                factor = sum / 10;
                tmp.next = new ListNode(sum % 10);
                tmp = tmp.next;
            }
            if (factor != 0) {
                tmp.next = new ListNode(factor);
            }
            return curHead.next;
        }
    }
}
